package util;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

public class FArquivo {

	public static String criaTmp(File fonte, String extensao, String path){
		
		//Criar copia temporaria para o browser nao usar a cache
		boolean c = false;
		int t = 0;
		String tmpS = "";
		String tmpF = "";
		File tmpFile = null;
		File tmpFinal = null;
		for(t=0; t<30000; t++){
			tmpS = "tmp"+t+"."+extensao;
			tmpFile = new File(path+tmpS);
			if(c){
				tmpF = tmpS;
				tmpFinal = new File(path+tmpF);
				break;
			}
			if(tmpFile.exists()){
				tmpFile.delete();
				c = true;
			}
		}
		if(tmpFinal==null){
			tmpF = "tmp0."+extensao;
			tmpFinal = new File(path+tmpF);
		}
		
		try{
		//Copiar o arquivo carregado para o tmp correto.
		FileInputStream fis  = new FileInputStream(fonte);
        FileOutputStream fos = new FileOutputStream(tmpFinal);
        byte[] buf = new byte[1024];
        int i = 0;
        while((i=fis.read(buf))!=-1) {
            fos.write(buf, 0, i);
        }
        fis.close();
        fos.close();
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return tmpF;
	}
	
	public static String md5_hex(byte[] texto){  
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");  
			BigInteger hash = new BigInteger(1, md.digest(texto));  
			String s = hash.toString(16);  
			if (s.length() %2 != 0)  
				s = "0" + s;  
			return s;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}  
	} 
	
}
